import os
import sys
import time
import traceback

TIMEOUT = 10
LAUNCH_TIMEOUT = 30
LOGIN_TIMEOUT = 30
MARKER = '\x01d(^-^)b\x02'


def launch_kakaotalk():
  openApp("C:\\Program Files (x86)\\Kakao\\KakaoTalk\\KakaoTalk.exe")
  wait("1517409742646.png", LAUNCH_TIMEOUT)

  kakaotalk = App("KakaoTalk")
  kakaotalk.open("C:\\Program Files (x86)\\Kakao\\KakaoTalk\\KakaoTalk.exe")
  wait("1517409742646.png", TIMEOUT)
  return kakaotalk


def do_login(id, password, force=True):
  click("1517394455296.png")
  type("a", KEY_CTRL)
  type(id)
  type(Key.TAB)
  type(password)
  click("1517395444340.png")
  while wait("1517395681120.png", TIMEOUT) is None:
    if not force:
      raise Exception("Login failed: TIMEOUT")
    if (wait("1517472228546.png", TIMEOUT) is None or click("1517472228546.png") is None):
      raise Exception("Login failed: TIMEOUT")

  return True


def open_chat(app, chat_icon):
  click("1517577683635.png")
  if wait("1517659457362.png", TIMEOUT) is None:
    raise Exception("Cannot find a chat room")
  doubleClick("1517659457362.png")
  time.sleep(5)
  if wait("1517660248738.png", TIMEOUT) is None:
    raise Exception("Cannot open chat window")


def get_chat_history():
  if wait("1517662580677.png", TIMEOUT) is None:
    raise Exception("Cannot find chat window")
  click("1517662580677.png")
  type("a", KEY_CTRL)
  type("c", KEY_CTRL)

  return App.getClipboard()


def get_credentials():
  if len(sys.argv) != 3:
    print "Usage> %s [ID] [PASSWORD]" % sys.argv[0]
    sys.exit(0)
  id, password = sys.argv[1:3]
  return (id, password)


def kill_kakaotalk():
  closeApp("KakaoTalk.exe")
  os.system("TASKKILL /IM KakaoTalk.exe")
  time.sleep(1)


def main():
  setFindFailedResponse(SKIP)
  (id, password) = get_credentials()

  kill_kakaotalk()
  app = launch_kakaotalk()
  do_login(id, password)
  open_chat(app, "1517659457362.png")
  history = get_chat_history()

  print MARKER + repr(history) + MARKER
  kill_kakaotalk()
  return 0


if __name__ == '__main__':
  main()
